from rest_framework.views import APIView
from rest_framework.response import Response
from utils.response import *
import requests
from bs4 import BeautifulSoup


class SakuraAPI(APIView):
    def get(self, request):
        if request.method == 'GET':
            search = request.GET.get('search')
            response['data'] = []
            if search is None or search == '':
                nothing['error'] = '你没有输入任何东西'
                return Response(nothing)
            else:
                url = f'https://www.yhdmw.com/comicsearch/-------------.html?wd={search}&submit='
                util_url = 'https://www.yhdmw.com/'
                resp = requests.get(url)
                main_page = BeautifulSoup(resp.text, 'html.parser')
                src = main_page.find_all('a', attrs={
                    'class': 'myui-vodlist__thumb img-lg-150 img-md-150 img-sm-150 img-xs-100 lazyload'
                })
                for i in src:
                    href = util_url + i.get('href').strip('/')
                    title = i.get('title')
                    img = util_url + i.get('data-original').strip('/')
                    dic = {
                        'name': title,
                        'url': href,
                        'img': img
                    }
                    response['data'].append(dic)
                    response['total'] = len(response['data'])
                return Response(response)

